package com.example.demo.leetcode.file;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.TreeSet;

public class SimpleTreeSetHandler {

    private Integer[] datas = null;

    /**
     * 排序
     * @param in 数据文件路径
     */
    public void sort(String in){
        long t1 = System.currentTimeMillis();
        File file = new File(in);
        if(!file.exists())
            return;

        try(BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file),"UTF-8"));){
            TreeSet<Integer> set = new TreeSet<>();
            String line = null;
            while((line = reader.readLine()) != null && !"".equals(line)){
                set.add(new Integer(line));
            }
            this.datas = set.toArray(new Integer[set.size()]);
        }catch(Exception e){
            e.printStackTrace();
        }
        long t2 = System.currentTimeMillis();

        System.out.println("排序完成！耗时：" + (t2 - t1) + "毫秒。");
    }

    /**
     * 从pos开始，获取count个数
     * @param pos
     * @param count
     * @return
     */
    public Integer[] limit(int pos, int count){
        long t1 = System.currentTimeMillis();
        if(pos < 0 || count <= 0){
            return null;
        }
        Integer[] result = new Integer[count];
        for (int i = 0; i < count && pos + i < this.datas.length; i++) {
            result[i] = this.datas[pos + i];
        }
        long t2 = System.currentTimeMillis();
        System.out.println("取数成功！耗时：" + (t2 - t1) + "毫秒。");
        return result;
    }

    // 测试：
    // 创建1千万随机数，进行排序
    public static void main(String[] args) {
//        main.java.com.example.demo.leetcode.file.DataProducer.produce(10000000, "data");

        SimpleTreeSetHandler handler = new SimpleTreeSetHandler();
        handler.sort("data");

        Integer[] limit = handler.limit(10, 10);
        System.out.println(Arrays.asList(limit));
    }
}
